package com.crrc.sandameter.view

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.crrc.sandameter.R
import com.crrc.sandameter.common.CommonHolder
import com.crrc.sandameter.entity.TaskEntity

class TaskEntityListAdapter(private val taskList: List<TaskEntity>,
    private val itemClickListener: (TaskEntity) -> Unit) : RecyclerView.Adapter<CommonHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommonHolder {
        return CommonHolder(LayoutInflater.from(parent.context)
            .inflate(R.layout.item_task, parent, false))
    }

    override fun getItemCount(): Int {
        return taskList.size
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onBindViewHolder(holder: CommonHolder, position: Int) {
        val task = taskList[position]
        val taskNameTv = holder.itemView.findViewById<TextView>(R.id.task_name_tv)
        val markIv = holder.itemView.findViewById<ImageView>(R.id.mark_iv)
        taskNameTv.text = task.trainCode
        holder.itemView.setOnClickListener {
            if (!task.isSeleted) {
                taskList.forEach { it.isSeleted = false }
                task.isSeleted = true
                notifyDataSetChanged()
                itemClickListener.invoke(task)
            }
        }
        if (task.isSeleted) {
            markIv.visibility = ViewGroup.VISIBLE
        } else {
            markIv.visibility = ViewGroup.INVISIBLE
        }
    }
}